<?php

namespace app\api\controller;



use app\admin\model\Order;
use app\api\service\MemorderService;
use app\api\service\OrderService;
use app\api\service\SignService;
use app\common\controller\Api;
use app\common\model\monthly\card\Payments;
use app\common\model\Payment;
use app\common\model\ScoreOrder;
use DateTime;
use think\Db;

class Notify extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    protected function handleCallback($xml)
    {
        // 解析 XML
        $message = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $message = json_encode($message);
        $message = json_decode($message, true);

        // 记录日志
        $logId = db::name('pay_log')->insertGetId([
            'open_id'       => $message['openid'],
            'mch_id'        => $message['mch_id'],
            'out_trade_no'  => $message['out_trade_no'],
            'pay_money'     => $message['total_fee'] / 100,
            'transaction_id' => $message['transaction_id'],
            'app_id'        => $message['appid'],
            'status'        => 1,
            'pay_time'      => time(),
            'response'      => json_encode($message),
        ]);

        // 检查返回码和结果码
        if ($message['return_code'] === 'SUCCESS' && $message['result_code'] === 'SUCCESS') {
            return ['status' => 'success', 'message' => $message];
        }

        // 处理失败情况
        db::name('pay_log')->where('id', $logId)->update(['status' => 0, 'error_message' => 'Payment failed: ' . $message['result_code']]);

        // 记录错误日志
        error_log('Payment failed: ' . $message['result_code']);

        return ['status' => 'fail', 'logId' => $logId];
    }

    //预约回调
    public function reservation_pay()
    {
        $xml = file_get_contents('php://input');
        $result = $this->handleCallback($xml);
        // 根据处理结果生成响应
        if ($result['status'] === 'success') {
            $Reservations= \app\common\model\Reservations::where('order_no','=', $result['message']['out_trade_no'])->find();
            \app\common\model\Reservations::where('order_no','=', $result['message']['out_trade_no'])->update(['deposit_status'=>1,'pay_time'=>time()]);
            \app\common\model\User::money(-$Reservations['balance_deduction'],$Reservations['user_id'],'支付押金');
            exit('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>');
        } else {
            exit('<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>');
        }
        return true;
    }

    //结算回调
    public function order_pay()
    {
        $xml = file_get_contents('php://input');
        $result = $this->handleCallback($xml);
        // 根据处理结果生成响应
        if ($result['status'] === 'success') {
            $order = Payment::where('order_no', '=',  $result['message']['out_trade_no'])->find();
            // 统一处理订单回调
            $server=new OrderService();
            $server->order_success($order['id']);
            exit('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>');
        } else {
            exit('<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>');
        }
        return true;
    }

    //月卡回调
    public function car_pay()
    {
        $xml = file_get_contents('php://input');
        $result = $this->handleCallback($xml);
        // 根据处理结果生成响应
        if ($result['status'] === 'success') {
            $Payments = Payments::where('order_no', '=',  $result['message']['out_trade_no'])->find();
            if($Payments['pay_status']==0){
              $user=  \app\common\model\User::where('id',$Payments['user_id'])->find();
                $currentMonthCardTime = new DateTime($user->month_card_time);

                $monthsToAdd =$Payments['months'];
                $currentMonthCardTime->modify("+{$monthsToAdd} months");

                $user->month_card_time = $currentMonthCardTime->format('Y-m-d H:i:s'); // 格式化为 datetime 格式
                $user->month_card = $user->month_card+$Payments['usage_count'];
                $user->save(); // 保存更改
               Payments::where('order_no', '=',  $result['message']['out_trade_no'])->update(['pay_status'=>1,'pay_time'=>time()]);
            }
            exit('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>');
        } else {
            exit('<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>');
        }
        return true;
    }

    //充值支付回调
    public function recharge_pay()
    {
        $xml = file_get_contents('php://input');
        $result = $this->handleCallback($xml);
        // 根据处理结果生成响应
        if ($result['status'] === 'success') {
            $Payments = \app\common\model\recharge\Payments::where('order_no', '=',  $result['message']['out_trade_no'])->find();
            if($Payments['pay_status']==0){
                $user=  \app\common\model\User::where('id',$Payments['user_id'])->find();
                \app\common\model\User::money($Payments['recharge_amount']+$Payments['bonus_amount'],$Payments['user_id'],'余额充值');

                \app\common\model\recharge\Payments::where('order_no', '=',  $result['message']['out_trade_no'])->update(['pay_status'=>1,'pay_time'=>time()]);
            }
            exit('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>');
        } else {
            exit('<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>');
        }
        return true;
    }


    //会员商城回调
    public function mem_order_pay()
    {
        $xml = file_get_contents('php://input');
        $result = $this->handleCallback($xml);
        // 根据处理结果生成响应
        if ($result['status'] === 'success') {
            $order = \app\common\model\member\Order::where('order_no', '=',  $result['message']['out_trade_no'])->find();
            // 统一处理订单回调
            $server=new MemorderService();
            $server->order_success($order['id']);
            exit('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>');
        } else {
            exit('<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>');
        }
        return true;
    }


    //兑换商品 邮费
    public function sign_pay()
    {
        $xml = file_get_contents('php://input');
        $result = $this->handleCallback($xml);
        // 根据处理结果生成响应
        if ($result['status'] === 'success') {
            $order = ScoreOrder::where('order_no', '=',  $result['message']['out_trade_no'])->find();
            // 统一处理订单回调
            $server=new SignService();
            $server->order_success($order['id']);
            exit('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>');
        } else {
            exit('<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[ERROR]]></return_msg></xml>');
        }
        return true;
    }

}
